package com.metagurukul.metaspace.actions;

import java.sql.SQLException;

import javax.mail.internet.AddressException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.metagurukul.metaspace.controller.ResendPasswordForm;
import com.metagurukul.metaspace.models.beans.UserLoginDetail;
import com.metagurukul.metaspace.service.UserService;
import com.metagurukul.metaspace.util.EmailSender;
import com.metagurukul.metaspace.util.PasswordGenerator;
import com.metagurukul.metaspace.validator.Validator;

/**
 * Represents Action class which resends password to the user if user demands it
 * again on signUp or Forgot his password;
 * 
 * @author bhagyesh
 * @see Action
 */
public class ResendPasswordAction extends Action {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws SQLException,AddressException {
		ResendPasswordForm resendPasswordForm = (ResendPasswordForm) form;
		String emailId = resendPasswordForm.getEmailId();
		Validator validate = new Validator();
		if (!validate.validateEmail(emailId)
				|| (!emailId.endsWith("@metacube.com") && !emailId
						.endsWith("@metagurukul.com"))) {
			ActionMessages errors = new ActionMessages();
			errors.add("emailId", new ActionMessage("error.emailId.invalid"));
			saveErrors(request, errors);
			return mapping.getInputForward();
		}
		PasswordGenerator passwordGenerator = new PasswordGenerator();
		String password = passwordGenerator.getPassword();
		request.setAttribute("mail", emailId);
		if (updateLoginDetail(emailId, password)) {
			EmailSender emailSender = new EmailSender();
			emailSender.sendPassword(emailId, password);
			return mapping.findForward("success");
		} else {
			ActionMessages errors = new ActionMessages();
			errors.add("emailId",
					new ActionMessage("error.resendPassword.fail"));
			saveErrors(request, errors);
			return mapping.getInputForward();
		}
	}

	/**
	 * Update the password for the User as a newly generated password will be sent
	 * to the user.
	 * 
	 * @param emailId
	 * @param password
	 * @return
	 * @throws SQLException
	 */
	public boolean updateLoginDetail(String emailId, String password)
			throws SQLException {
		UserLoginDetail userLoginDetail = new UserLoginDetail();
		userLoginDetail.setEmailId(emailId);
		userLoginDetail.setPassword(password);
			return (UserService.updateUserLoginDetail(userLoginDetail) > 0);
	}
}
